//
//  PictureViewController.m
//  Estate
//
//  Created by heyong on 16/5/30.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "PictureViewController.h"


#import "PictureCell.h"
#import "LSTarBrowser.h"
#import "TypeModel.h"
#import <Photos/Photos.h>
#import "MJPhotoBrowser.h"

@interface PictureViewController ()
{
    //记录要删除的cell;
    NSIndexPath *delIndexPath;
    //记录上一次删除的cell;
    NSIndexPath *lastDelIndexPath;
}

// 编辑栏view
@property (nonatomic, strong) UIView *editView;
//点击事件图片存储
@property(strong, nonatomic)NSMutableArray *cilckImagArray;

@end

@implementation PictureViewController

- (NSMutableArray *)cilckImagArray{
    if(!_cilckImagArray){
        _cilckImagArray=[NSMutableArray array];
    }
    return _cilckImagArray;
}


- (UIView *)editView {
    if (!_editView) {
        _editView = [[UIView alloc] initWithFrame:CGRectMake(0, DEF_SCREEN_HEIGHT - 50, DEF_SCREEN_WIDTH, 50)];
        _editView.backgroundColor = UIColorFromRGB(0xd2d3d4);
        
        // 保存
        UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_editView addSubview:saveBtn];
        [saveBtn setBackgroundImage:[UIImage imageNamed:@"xiazai"] forState:UIControlStateNormal];
        saveBtn.frame = CGRectMake(10, 10, 30, 30);
        [saveBtn addTarget:self action:@selector(saveImageToAlbum) forControlEvents:UIControlEventTouchUpInside];
        
        //右上方确认按钮
        NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
        if ([role isEqualToString:@"USER_01"] || [role isEqualToString:@"USER_03"]|| [role isEqualToString:@"USER_07"]) {
            // 跳转
            UIButton *jumpBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [_editView addSubview:jumpBtn];
            [jumpBtn setBackgroundImage:[UIImage imageNamed:@"jilu"] forState:UIControlStateNormal];
            jumpBtn.frame = CGRectMake(DEF_SCREEN_WIDTH/2 - 15, 10, 30, 30);
            [jumpBtn addTarget:self action:@selector(jump) forControlEvents:UIControlEventTouchUpInside];
        }
        
        // 删除
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_editView addSubview:deleteBtn];
        [deleteBtn setBackgroundImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
        deleteBtn.frame = CGRectMake(DEF_SCREEN_WIDTH - 40, 10, 30, 30);
        [deleteBtn addTarget:self action:@selector(deleteImage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _editView;
}

- (UIView *)alertView{
    if(!_alertView){
        _alertView=[[UIView alloc]initWithFrame:self.view.bounds];
    }
    return _alertView;
}
- (NSMutableArray *)imageArray{
    if(_imageArray==nil){
        _imageArray=[NSMutableArray array];
    }
    return _imageArray;
}

- (NSMutableArray *)sortImageArray{
    if(_sortImageArray==nil){
        _sortImageArray=[NSMutableArray array];
    }
    return _sortImageArray;
}

- (NSMutableArray *)selectedImages {
    if(_selectedImages==nil){
        _selectedImages=[NSMutableArray array];
    }
    return _selectedImages;
}


- (UICollectionView *)collectionView {
    if(_collectionView==0){
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
        //设置行间距-最小行间距
        flowLayout.minimumLineSpacing=5;
        //设置每单元格左右间距
        flowLayout.minimumInteritemSpacing=5;
        //滑动的方向
        flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
        //设置view的周边间距
        flowLayout.sectionInset=UIEdgeInsetsMake(5, 5, 5, 5);
        //设置单元格的大小
        flowLayout.itemSize=CGSizeMake((DEF_WIDTH(self.view)-20)/3, (DEF_WIDTH(self.view)-10)/3);
        //设置滚动方向
        flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
        //设置fram
        self.collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, DEF_WIDTH(self.view), DEF_HEIGHT(self.view)) collectionViewLayout:flowLayout];
        //设置collection
        self.collectionView.delegate=self;
        self.collectionView.dataSource=self;
        self.collectionView.showsVerticalScrollIndicator=NO;
        self.collectionView.backgroundColor=[UIColor whiteColor];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.collectionView];
    self.title=@"本地图片";
    [self.collectionView registerClass:[PictureCell class] forCellWithReuseIdentifier:@"myCell"];
    //选择按钮隐藏
    
    //选择附件进入页面
    if([self.flag isEqualToString:@"file"]){
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
        self.isHidden=NO;
    } else {
        self.isHidden=YES;
        UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
        right.frame = CGRectMake(0, 0, 50, 50);
        [right setTitle:@"选择" forState:UIControlStateNormal];
        [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        right.titleLabel.font = [UIFont systemFontOfSize:16];
        [right addTarget:self action:@selector(poEditField) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem *rightBut = [[UIBarButtonItem alloc] initWithCustomView:right];
        self.navigationItem.rightBarButtonItem = rightBut;
    }
    
    //遍历沙盒里的文件
    NSString *fullPath=DEF_IMAGEFILE_PATH;
    //文件夹操作
    NSFileManager*fileManager = [NSFileManager defaultManager];
    //获取本地Documents路径
    NSArray*fileList = [[NSArray alloc]init];
    //得到目录下文件名
    fileList=[fileManager contentsOfDirectoryAtPath:fullPath error:nil];
    NSMutableArray *muTabfileLsit=[NSMutableArray arrayWithArray:fileList];
    
    //外部带入图片
    if(self.selectedImages.count>0){
        //传入图片名称解析
        NSMutableArray *temNameArr=[NSMutableArray array];
        for (NSString *str in self.selectedImages) {
            NSArray *strArr=[str componentsSeparatedByString:@"/"];
            //得到图片名称 唯一
            NSString *fileName=[strArr lastObject];
            [temNameArr addObject:fileName];
            if([fileList containsObject:fileName]){
                [muTabfileLsit removeObject:fileName];
            }
        }
        for(int i=0;i<muTabfileLsit.count;i++){
            NSString *tempPath=[fullPath stringByAppendingString:[NSString stringWithFormat:@"/%@",muTabfileLsit[i]]];
            //添加到显示数组
            [self.imageArray addObject:tempPath];
        }
        
    }else{
        for(int i=0;i<fileList.count;i++){
            NSString *tempPath=[fullPath stringByAppendingString:[NSString stringWithFormat:@"/%@",fileList[i]]];
            //添加到显示数组
            [self.imageArray addObject:tempPath];
        }
    }
    //图片数组倒序
    self.sortImageArray =(NSMutableArray *)[[self.imageArray reverseObjectEnumerator] allObjects];
    
    //添加手势
    if(![self.flag isEqualToString:@"file"]){
        //        /创建长按手势监听
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                                   initWithTarget:self
                                                   action:@selector(myHandleTableviewCellLongPressed:)];
        longPress.minimumPressDuration = 1.0;
        //将长按手势添加到需要实现长按操作的视图里
        //    [self.collectionView addGestureRecognizer:longPress];
    }
}

// 弹出编辑栏
- (void)poEditField {
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 50, 50);
    [right setTitle:@"取消" forState:UIControlStateNormal];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:16];
    [right addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBut = [[UIBarButtonItem alloc] initWithCustomView:right];
    self.navigationItem.rightBarButtonItem = rightBut;
    
    [self.view addSubview:self.editView];
    self.isHidden=NO;
    [self.collectionView reloadData];
}

// 取消编辑栏
- (void)cancel {
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 50, 50);
    [right setTitle:@"选择" forState:UIControlStateNormal];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:16];
    [right addTarget:self action:@selector(poEditField) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBut = [[UIBarButtonItem alloc] initWithCustomView:right];
    self.navigationItem.rightBarButtonItem = rightBut;
    
    [self.editView removeFromSuperview];
    //隐藏右上角按钮
    self.isHidden=YES;
    //清空已选图片
    [self.selectedImages removeAllObjects];
    
    [self.collectionView reloadData];
}

#pragma mark -保存图片
- (void)clickSave {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //文件复制到附件文件夹
    for (NSString *imgUrl in self.selectedImages) {
        //得到文件名
        NSString *imageName= [[imgUrl componentsSeparatedByString:@"/"]lastObject];
        //目标文件
        NSString *fileUrl=[NSString stringWithFormat:@"/%@",imageName];
        if(![fileManager fileExistsAtPath:[DEF_FILE_PATH stringByAppendingString:fileUrl]]){
            //移动到附件文件夹
            [fileManager copyItemAtPath:imgUrl toPath:[DEF_FILE_PATH stringByAppendingString:fileUrl] error:nil];
        }else{
            NSLog(@"图片存在");
        }
    }
    
    //    if([self.flag isEqualToString:@"file"]){
    if(self.selectedImageBlock){
        self.selectedImageBlock(self.selectedImages);
    }
    //记录
    NSNotification *notice = [NSNotification notificationWithName:@"RefreshImage" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    
    //旁站
    NSNotification * notice1 = [NSNotification notificationWithName:@"RefreshImage_1" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice1];
    
    NSNotification * notice2 = [NSNotification notificationWithName:@"RefreshImage_2" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice2];
    
    NSNotification * notice3 = [NSNotification notificationWithName:@"RefreshImage_3" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice3];
    
    NSNotification * notice4 = [NSNotification notificationWithName:@"RefreshImage_4" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice4];
    
    NSNotification * notice5 = [NSNotification notificationWithName:@"RefreshImage_5" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice5];
    
    //日记
    NSNotification * notice6 = [NSNotification notificationWithName:@"RefreshImage_rj" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice6];
    
    NSNotification * notice6_1 = [NSNotification notificationWithName:@"RefreshImage_rj_1" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice6_1];
    
    // 验收
    NSNotification * notice7 = [NSNotification notificationWithName:@"RefreshImage_ys" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice7];
    
    // 跟进
    NSNotification * notice8 = [NSNotification notificationWithName:@"RefreshImage_gj" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice8];
    
    // 施工方待办编辑
    NSNotification * notice9 = [NSNotification notificationWithName:@"RefreshImage_sgf" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice9];
    
    // 施工方编辑验收(验收不合格时)
    NSNotification * notice10 = [NSNotification notificationWithName:@"RefreshImage_editYS" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice10];
    
    // 见证取样
    NSNotification * notice11 = [NSNotification notificationWithName:@"RefreshImage_jzqy" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice11];
    
    // 巡检员
    NSNotification * notice12 = [NSNotification notificationWithName:@"RefreshImage_xjy" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice12];
    
    // 巡检总监
    NSNotification * notice13 = [NSNotification notificationWithName:@"RefreshImage_xjzj" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice13];
    
    // 巡检组长
    NSNotification * notice14 = [NSNotification notificationWithName:@"RefreshImage_xjzz" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice14];
    
    // 安全
    NSNotification *notice15 = [NSNotification notificationWithName:@"RefreshImage_safe" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice15];
    
    // 巡视
    NSNotification *notice16 = [NSNotification notificationWithName:@"RefreshImage_patrol" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice16];
    
    // 总监编辑跟进
    NSNotification *notice17 = [NSNotification notificationWithName:@"RefreshImage_directorEditFollow" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notice17];
    
    [self.navigationController popViewControllerAnimated:YES];
    
    //    } else {
    //        if(self.selectedImages.count > 0){
    //            //跳转到位置
    //            OrientationViewController *orienta=[[OrientationViewController alloc]init];
    //            orienta.imageArray=self.selectedImages;
    //            [self.navigationController pushViewController:orienta animated:YES];
    //        }
    //    }
}

#pragma mark - UICollectionViewDelegate
///返回组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//返回每组个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.sortImageArray.count;
}

// 返回内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
    //    设置图片
    NSString *imagePath = self.sortImageArray[indexPath.row];
    
    //原图
    UIImage *artworkMaster=[UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
    //设置缩略图
    UIImage *image=[LSUtility thumbnailWithImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]] size:CGSizeMake((DEF_WIDTH(self.view)-20)/3, (DEF_WIDTH(self.view)-10)/3)];
    
    cell.pictureImg.contentMode =UIViewContentModeScaleAspectFill;
    cell.pictureImg.clipsToBounds =YES;
    cell.pictureImg.image = image;
    
    
    [self.cilckImagArray addObject:artworkMaster];
    
    
    //设置行数为tag
    cell.selBtn.tag = indexPath.row;
    
    //长按删除
    if (indexPath == delIndexPath) {
        cell.isDel = YES;
    } else {
        cell.isDel=NO;
    }
    //是否隐藏右上角对勾按钮
    cell.selBtn.hidden= self.isHidden;
    
    // 设置选中  解决图片过多 滑动 复用问题
    if( [self.selectedImages containsObject:imagePath]){
        cell.selBtn.selected = YES;
    }else{
        cell.selBtn.selected = NO;
    }
    
    // __block PictureCell *cellBlock = cell;
    [cell.selBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

// 选中图片
-(void)clickBtn:(UIButton *)sender {
    // 设置图片
    NSString *imagePath = self.sortImageArray[sender.tag];
    
    //未设置长按 这个方法不管
    if (delIndexPath) {
        // 选中的照片中存在删除的这张照片，移除掉。
        if([self.selectedImages containsObject:imagePath]){
            [self.selectedImages removeObject:imagePath];
        }
        //本地数据源删除
        [self.sortImageArray removeObject:imagePath];
        [self.collectionView reloadData];
        // 清空删除的cell
        delIndexPath = nil;
        
        //沙盒文件删除
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager removeItemAtPath:imagePath error:NULL]) {
            NSLog(@"删除图片成功");
        }
        //刷新首页本地图片数量
        NSNotification * indexNum = [NSNotification notificationWithName:@"indexView" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter] postNotification:indexNum];
        
    } else {
        
        if ([self.flag isEqualToString:@"file"]) {
            //附件大于8张
            if(self.selectedImages.count>8){
                if(sender.selected){
                    sender.selected=NO;
                    [self.selectedImages removeObject:imagePath];
                    return;
                }
                kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一些照片再选择呗～");
                if(sender.selected) {
                    sender.selected = !sender.selected;
                    [self.selectedImages removeObject:imagePath];
                }
            }else{
                sender.selected = !sender.selected;
                if(sender.selected){
                    [self.selectedImages addObject:imagePath];
                }else{
                    [self.selectedImages removeObject:imagePath];
                }
            }
        } else {
            sender.selected = !sender.selected;
            if (sender.selected) {
                [self.selectedImages addObject:imagePath];
            } else {
                [self.selectedImages removeObject:imagePath];
            }
        }
    }
}

//点击视图放大
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    PictureCell *cell=(PictureCell *)[collectionView cellForItemAtIndexPath:indexPath];
//    NSString *imagePath= self.sortImageArray[indexPath.row];
//    UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
//    cell.pictureImg.image=image;
//    
//    [LSTarBrowser showImage:cell.pictureImg];
    
    
    NSMutableArray *photos = [NSMutableArray array];
    
    for (int i = 0; i < self.sortImageArray.count; i++) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.image = self.sortImageArray[i];
        [photos addObject:photo];
    }
    
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = indexPath.row;
    browser.photos = photos; // 设置所有的图片
    browser.showSaveBtn = NO;
    [browser show];
    
}

- (void)myHandleTableviewCellLongPressed:(UILongPressGestureRecognizer *)gestureRecognizer {
    CGPoint pointTouch = [gestureRecognizer locationInView:self.collectionView];
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:pointTouch];
        if (indexPath == nil) {
            NSLog(@"空");
        }else{
            delIndexPath = indexPath;
            
            if(lastDelIndexPath==delIndexPath){
                delIndexPath=nil;
            }else{
                lastDelIndexPath=delIndexPath;
            }
            //            NSLog(@"Section = %ld,Row = %ld",(long)indexPath.section,(long)indexPath.row);
            //            PictureCell *cell= (PictureCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            [self.collectionView reloadData];
        }
    }
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        //        NSLog(@"UIGestureRecognizerStateChanged");
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        //        NSLog(@"UIGestureRecognizerStateEnded");
    }
}


#pragma  mark - 二期新需求 新增方法

// 保存照片到本地相册
- (void)saveImageToAlbum {
    if (self.selectedImages.count > 0) {
        
        for (NSString *imagePath in self.selectedImages) {
            UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
            [self getAuthorityWithImage:image];
        }
    } else {
        [LSUtility showToastWithMessage:@"请选择照片" inView:self.view Andtime:1.];
    }
}

// 授权
- (void)getAuthorityWithImage:(UIImage *)image {
    // 获取当前App的相册授权状态
    PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];
    
    // 判断授权状态
    if (authorizationStatus == PHAuthorizationStatusAuthorized) {
        // 如果已经授权, 保存图片
        [self saveImage:image];
        
        // 如果没决定, 弹出指示框, 让用户选择
    } else if (authorizationStatus == PHAuthorizationStatusNotDetermined) {
        
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            
            // 如果用户选择授权, 则保存图片
            if (status == PHAuthorizationStatusAuthorized) {
                [self saveImage:image];
            }
        }];
    } else {
        [LSUtility showToastWithMessage:@"请在设置界面, 授权访问相册." inView:self.view Andtime:2.0];
    }
}

// 保存图片
- (void)saveImage:(UIImage *)image {
    NSLog(@"%@",image);
    // 获取相片库对象
    PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
    // 调用changeBlock
    [library performChanges:^{
        
        // 2.4 根据传入的相片, 创建相片变动请求
        PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        // 判断是否出错, 如果报错, 声明保存不成功
        if (error) {
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
            [SVProgressHUD showSuccessWithStatus:@"保存照片到相册失败"];
            
        } else {
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
            [SVProgressHUD showSuccessWithStatus:@"已成功保存到本地相册"];
        }
    }];
}

// 跳转到工作记录
- (void)jump {
    if(self.selectedImages.count > 0) {
        //右上方确认按钮
        NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
        if(self.selectedImages.count>=9){
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一些照片再选择呗～");
        }else{
            if ([USERTYPE.typeArray containsObject:role] || [USERTYPE.typeArrayNoWeather containsObject:role]) {
                
            } else {
                //跳转到位置
                OrientationViewController *orienta=[[OrientationViewController alloc]init];
                orienta.imageArray = self.selectedImages;
                [self.navigationController pushViewController:orienta animated:YES];
            }
        }
    } else {
        [LSUtility showToastWithMessage:@"请选择照片" inView:self.view Andtime:1.];
    }
}

// 删除照片
- (void)deleteImage {
    if (self.selectedImages.count > 0) {
        NSString *str = [NSString stringWithFormat:@"%d张照片将从您的设备中删除", self.selectedImages.count];
        NSRange range = [str rangeOfString:@"张"];
        
        //改变message的大小和颜色
        NSMutableAttributedString *messageAtt = [[NSMutableAttributedString alloc] initWithString:str];
        [messageAtt addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17*BIZ] range:NSMakeRange(0, str.length)];
        [messageAtt addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, range.location + 1)];
        
        [self popupView:messageAtt];
        
    } else {
        [LSUtility showToastWithMessage:@"请选择照片" inView:self.view Andtime:1.];
    }
}

#pragma  mark - 弹出视图
- (void)popupView:(NSAttributedString *)msg{
    
    UIView *contentView=[[UIView alloc]initWithFrame:CGRECTS(0, 0, 300, 140)];
    contentView.center=self.view.center;
    contentView.backgroundColor=[UIColor whiteColor];
    contentView.layer.cornerRadius=10.;
    contentView.layer.borderColor=[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.00].CGColor;
    contentView.layer.borderWidth=1.;
    
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, DEF_WIDTH(contentView), 40*BIZ)];
    title.layer.cornerRadius=10.;
    title.backgroundColor=[UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1.00];
    title.textColor=[UIColor colorWithRed:0.51 green:0.51 blue:0.51 alpha:1.00];
    title.font=[UIFont systemFontOfSize:15.];
    title.text=@"删除照片";
    title.textAlignment=1;
    [contentView addSubview:title];
    
    //文字显示内容
    UILabel *contentText=[[UILabel alloc]initWithFrame:CGRectMake(0, 40*BIZ, DEF_WIDTH(contentView),60*BIZ)];
    contentText.textAlignment=1;
    contentText.textColor=[UIColor colorWithRed:0.49 green:0.49 blue:0.49 alpha:1.00];
    contentText.font=[UIFont systemFontOfSize:20.];
    [contentText setAttributedText:msg];
    [contentView addSubview:contentText];
    
    //设置lab上面的圆角
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:contentText.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = contentText.bounds;
    maskLayer.path = maskPath.CGPath;
    contentText.layer.mask  = maskLayer;
    
    //分割线
    UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0, 100*BIZ,  DEF_WIDTH(contentView), 1)];
    lineView.backgroundColor=[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
    [contentView addSubview:lineView];
    
    UIView *rowView=[[UIView alloc]init];
    rowView.backgroundColor=[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
    [contentView addSubview:rowView];
    [rowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(DEF_WIDTH(contentView)/2-0.5);
        make.width.offset(1);
        make.top.mas_equalTo(lineView.mas_bottom).offset(0);
        make.bottom.mas_equalTo(contentView.mas_bottom).offset(0);
    }];
    
    //确认btn
    UIButton *confirmBtn= [[UIButton alloc]init];
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
    confirmBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    confirmBtn.tag=100;
    [confirmBtn setTitleColor:[UIColor colorWithRed:0.50 green:0.50 blue:0.50 alpha:1.00] forState:UIControlStateNormal];
    [contentView addSubview:confirmBtn];
    
    [confirmBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.mas_equalTo(lineView.mas_bottom).offset(0);
        make.bottom.mas_equalTo(confirmBtn.mas_bottom).offset(0);
        make.width.offset(DEF_WIDTH(contentView)/2);
    }];
    
    //取消btn
    UIButton *closeBtn=[[UIButton alloc]init];
    closeBtn.titleLabel.font=[UIFont systemFontOfSize:16];
    [closeBtn setTitle:@"取消" forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor colorWithRed:0.50 green:0.50 blue:0.50 alpha:1.00] forState:UIControlStateNormal];
    [contentView addSubview:closeBtn];
    closeBtn.tag=103;
    [closeBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(rowView.mas_right).offset(10);
        make.top.mas_equalTo(lineView.mas_bottom).offset(0);
        make.bottom.mas_equalTo(confirmBtn.mas_bottom).offset(0);
        make.width.offset(DEF_WIDTH(contentView)/2);
    }];
    [self.alertView addSubview:contentView];
    
    [self.view addSubview:self.alertView];
}

//点击方法
-(void)clickAction:(UIButton *)sender{
    WEAKSELF
    NSInteger tag=sender.tag;
    if(tag==100){
        [self.alertView removeFromSuperview];
        // 确认回调
        for (NSString *imgUrl in weakSelf.selectedImages) {
            [weakSelf.imageArray removeObject:imgUrl];
            [weakSelf.sortImageArray removeObject:imgUrl];
            //沙盒文件删除
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager removeItemAtPath:imgUrl error:NULL]) {
                NSLog(@"删除图片成功");
            }
        }
        self.selectedImages = nil;
        [self.collectionView reloadData];
        //刷新首页本地图片数量
        NSNotification *indexNum = [NSNotification notificationWithName:@"indexView" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter] postNotification:indexNum];
        [LSUtility showToastWithMessage:@"删除成功!" inView:self.view Andtime:1.];
    }else{
        [self.alertView removeFromSuperview];
    }
}

#pragma  mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"内存警告");
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
